package com.xyz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xyz.dao.mapper.TemplatePlanDaoMapper;
import com.xyz.dto.SelectPageTaskDto;
import com.xyz.dto.SelectPageTempDto;
import com.xyz.dto.TemplatePlanDto;
import com.xyz.dto.UpkeepTemplateTaskDto;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.AsyncPlanService;
import com.xyz.service.CommonService;
import com.xyz.service.TemplatePlanService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.GridData;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional(rollbackFor = Exception.class)
public class TemplatePlanServiceImpl implements TemplatePlanService {


    @Autowired
    private TemplatePlanMapper templatePlanMapper;

    @Autowired
    private TemplateTaskInfoMapper templateTaskInfoMapper;

    @Autowired
    private TemplatePlanTaskMapper templatePlanTaskMapper;

    @Autowired
    private TemplatePlanPartMapper templatePlanPartMapper;

    @Autowired
    private EquipmentPlanTemplateMapper EquipmentPlanTemplateMapper;

    @Autowired
    private PlanInfoMapper planInfoMapper;

    @Autowired
    private TemplatePlanDaoMapper templatePlanDao;

    @Autowired
    private CommonService commonService;

    @Autowired
    private AsyncPlanService asyncPlanService;

    @Autowired
    private UpkeepTemplateTaskMapper upkeepTemplateTaskMapper;

    @Autowired
    private UpkeepDbTaskMapper upkeepDbTaskMapper;

    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;

    @Autowired
    private UpkeepTemplateTaskPartMapper upkeepTemplateTaskPartMapper;

    @Autowired
    private PartInfoMapper partInfoMapper;

    /*
    * 模版列表查询
    * */
    @Override
    public DataResult getTemplatePlanAll(LoginInfo loginInfo, SelectPageTempDto selectPageTempDto) throws Exception {
        Page<TemplatePlan> pageObject = PageHelper.startPage(NumberUtil.parseInt(selectPageTempDto.getPageNum()), NumberUtil.parseInt(selectPageTempDto.getPageSize()));
        TemplatePlanExample tempExample = new TemplatePlanExample();
        TemplatePlanExample.Criteria tempCriteria = tempExample.createCriteria();
        if (StrUtil.isNotEmpty(selectPageTempDto.getTemplateName())) {
            tempCriteria.andTemplateNameLike("%" + selectPageTempDto.getTemplateName() + "%");
        }
        //业务类型
        if (StrUtil.isNotEmpty(selectPageTempDto.getBusinessType())) {
            tempCriteria.andBusinessTypeEqualTo(Integer.parseInt(selectPageTempDto.getBusinessType()));
        }
        //计划类型
        if (StrUtil.isNotEmpty(selectPageTempDto.getPlanType())) {
            tempCriteria.andPlanTypeEqualTo(Integer.parseInt(selectPageTempDto.getPlanType()));
        }
        //执行方式
        if (StrUtil.isNotEmpty(selectPageTempDto.getModeType())) {
            tempCriteria.andModeTypeEqualTo(Integer.parseInt(selectPageTempDto.getModeType()));
        }
        //状态
        if (StrUtil.isNotEmpty(selectPageTempDto.getState())) {
            tempCriteria.andStateEqualTo(Integer.parseInt(selectPageTempDto.getState()));
        }

        //设置组
        if (StrUtil.isNotEmpty(selectPageTempDto.getEmGroup())) {
            tempCriteria.andEmGroupEqualTo(Long.parseLong(selectPageTempDto.getEmGroup()));
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StrUtil.isNotEmpty(selectPageTempDto.getStartTime())) {
            tempCriteria.andFirstTimeGreaterThanOrEqualTo(sdf.parse(selectPageTempDto.getStartTime()));
        }

        if (StrUtil.isNotEmpty(selectPageTempDto.getEndTime())) {
            tempCriteria.andFirstTimeLessThanOrEqualTo(sdf.parse(selectPageTempDto.getEndTime()));
        }

        tempExample.setOrderByClause("create_time desc");
        List<TemplatePlan> templatePlanList = templatePlanMapper.selectByExample(tempExample);

        //获取数据
        List<Map<String, Object>> list = new ArrayList<>();
        for (TemplatePlan templatePlan : templatePlanList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", templatePlan.getId());
            map.put("templateName", templatePlan.getTemplateName());
            map.put("planType", templatePlan.getPlanType());
            if (templatePlan.getPlanType() == 1) {
                map.put("planTypeName", "维保计划");
            } else if (templatePlan.getPlanType() == 2) {
                map.put("planTypeName", "巡检计划");
            } else {
                map.put("planTypeName", "");
            }
            map.put("businessType", templatePlan.getBusinessType());
            map.put("state", templatePlan.getState());
            map.put("createTime", DateUtil.format(templatePlan.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            list.add(map);
        }
        //分页总数
        GridData gridData = new GridData(pageObject.getTotal(),list);
        return DataResult.build9100(gridData);
    }

    /*
     * 根据ID查询详情
     * */
    @Override
    public DataResult getTemplatePlanById(LoginInfo loginInfo, String id) throws Exception {
        TemplatePlan templatePlan = templatePlanMapper.selectByPrimaryKey(Long.parseLong(id));
        Map<String, Object> map = new HashMap<>();
        map.put("id", templatePlan.getId());
        map.put("templateName", templatePlan.getTemplateName());
        map.put("planType", templatePlan.getPlanType());
        map.put("state", templatePlan.getState());
        map.put("businessType", templatePlan.getBusinessType());
        map.put("dateInterval", templatePlan.getDateInterval());
        map.put("emGroup", templatePlan.getEmGroup());
        map.put("emSystem", templatePlan.getEmSystem());
        map.put("modeType", templatePlan.getModeType());
        map.put("planLocation", templatePlan.getPlanLocation());
        map.put("firstTime", DateUtil.format(templatePlan.getFirstTime(), "yyyy-MM-dd"));
        map.put("planStartTime", DateUtil.format(templatePlan.getPlanStartTime(), "yyyy-MM-dd"));
        map.put("planEndTime", DateUtil.format(templatePlan.getPlanEndTime(), "yyyy-MM-dd"));
        return DataResult.build9100(map);
    }

    /*
     * 根据ID查询工作项详情
     * */
    @Override
    public DataResult getTemplatePlanTaskById(LoginInfo loginInfo, String id) throws Exception {
        return DataResult.build9100(templatePlanDao.selectTemplatePlanTaskByTempId(Long.parseLong(id)));
    }

    /*
     * 根据ID查询零件详情
     * */
    @Override
    public DataResult getTemplatePartById(LoginInfo loginInfo, String id) throws Exception {
        return DataResult.build9100(templatePlanDao.selectTemplatePlanPartByTempId(Long.parseLong(id)));
    }

    /*
    * 任务项列表
    * */
    @Override
    public DataResult getTemplatePlanTask(LoginInfo loginInfo, SelectPageTaskDto selectPageTaskDto) throws Exception {
        Page<TemplateTaskInfo> pageObject = PageHelper.startPage(NumberUtil.parseInt(selectPageTaskDto.getPageNum()), NumberUtil.parseInt(selectPageTaskDto.getPageSize()));
        TemplateTaskInfoExample taskExample = new TemplateTaskInfoExample();
        TemplateTaskInfoExample.Criteria taskCriteria = taskExample.createCriteria();
        if (StrUtil.isNotEmpty(selectPageTaskDto.getTaskName())) {
            taskCriteria.andTaskNameLike("%" + selectPageTaskDto.getTaskName() + "%");
        }
        //业务类型
        if (StrUtil.isNotEmpty(selectPageTaskDto.getBusinessType())) {
            taskCriteria.andBusinessTypeEqualTo(Integer.parseInt(selectPageTaskDto.getBusinessType()));
        }
        //计划类型
        if (StrUtil.isNotEmpty(selectPageTaskDto.getPlanType())) {
            taskCriteria.andPlanTypeEqualTo(Integer.parseInt(selectPageTaskDto.getPlanType()));
        }

        if(StrUtil.isNotEmpty(selectPageTaskDto.getIds())){
            String ids = selectPageTaskDto.getIds();
            String[] split = ids.split(",");
            List<Long> idList = new ArrayList<>();
            for (String sp : split) {
                idList.add(Long.parseLong(sp));
            }
            taskCriteria.andIdNotIn(idList);
        }

        List<TemplateTaskInfo> templateTaskInfoList = templateTaskInfoMapper.selectByExample(taskExample);
        Map<Integer, String> dictMap = commonService.getDictMap("TYPE_TEMPLATE_TYPE");
        //获取数据
        List<Map<String, Object>> list = new ArrayList<>();
        for (TemplateTaskInfo templateTaskInfo : templateTaskInfoList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", templateTaskInfo.getId());
            map.put("taskName", templateTaskInfo.getTaskName());
            map.put("taskDesc", templateTaskInfo.getTaskDesc());
            if (templateTaskInfo.getPlanType() == 1) {
                map.put("planTypeName", "维保计划");
            } else if (templateTaskInfo.getPlanType() == 2) {
                map.put("planTypeName", "巡检计划");
            } else {
                map.put("planTypeName", "");
            }
            map.put("businessType", dictMap.getOrDefault(templateTaskInfo.getBusinessType(),""));
            list.add(map);
        }
        //分页总数
        GridData gridData = new GridData(pageObject.getTotal(),list);
        return DataResult.build9100(gridData);
    }

    /*
    * 保存模板基础信息
    * */
    @Override
    public DataResult insertTemplatePlan(LoginInfo loginInfo, TemplatePlanDto templatePlanDto) throws Exception {
        TemplatePlan templatePlan = new TemplatePlan();
        templatePlan.setState(1);
        templatePlan.setDateInterval(Integer.parseInt(templatePlanDto.getDateInterval()));
        templatePlan.setPlanType(Integer.parseInt(templatePlanDto.getPlanType()));
        templatePlan.setBusinessType(Integer.parseInt(templatePlanDto.getBusinessType()));
        templatePlan.setModeType(Integer.parseInt(templatePlanDto.getModeType()));
        templatePlan.setTemplateName(templatePlanDto.getTemplateName());
        templatePlan.setPlanStartTime(DateUtil.parseDate(templatePlanDto.getPlanStartTime()));
        templatePlan.setPlanEndTime(DateUtil.parseDate(templatePlanDto.getPlanEndTime()));
        DateTime firstDateTime = DateUtil.parseDate(templatePlanDto.getFirstTime());
        templatePlan.setFirstTime(firstDateTime);
        boolean in = DateUtil.isIn(templatePlan.getFirstTime(), templatePlan.getPlanStartTime(), templatePlan.getPlanEndTime());
        if(!in){
            return DataResult.build9250("首次执行日期必须在计划周期以内！");
        }
        if(firstDateTime.isBefore(DateUtil.date())){
            return DataResult.build9250("首次执行日期必须在当前时间以后！");
        }
        if(StrUtil.isBlank(templatePlanDto.getPlanLocation())){
            templatePlan.setPlanLocation("");
        }else {
            templatePlan.setPlanLocation(templatePlanDto.getPlanLocation());
        }
        templatePlan.setUpdateTime(new Date());
        templatePlan.setCreateTime(new Date());
        templatePlanMapper.insert(templatePlan);
        return DataResult.build9100(templatePlan.getId());
    }

    /*
    * 编辑模板基础信息
    * */
    @Override
    public DataResult updateTemplatePlan(LoginInfo loginInfo, TemplatePlanDto templatePlanDto) throws Exception {
        if(StrUtil.isBlank(templatePlanDto.getId())){
            return DataResult.build9250("参数id不能为空！");
        }

        TemplatePlan getTemplatePlan = templatePlanMapper.selectByPrimaryKey(Long.parseLong(templatePlanDto.getId()));
        if (getTemplatePlan.getState() != 1) {
            return DataResult.build9250("草稿状态的计划模板才能修改！");
        }
        TemplatePlan templatePlan = new TemplatePlan();
        templatePlan.setId(Long.parseLong(templatePlanDto.getId()));
        templatePlan.setDateInterval(Integer.parseInt(templatePlanDto.getDateInterval()));
        templatePlan.setPlanType(Integer.parseInt(templatePlanDto.getPlanType()));
        templatePlan.setBusinessType(Integer.parseInt(templatePlanDto.getBusinessType()));
        templatePlan.setModeType(Integer.parseInt(templatePlanDto.getModeType()));
        templatePlan.setTemplateName(templatePlanDto.getTemplateName());
        templatePlan.setPlanStartTime(DateUtil.parseDate(templatePlanDto.getPlanStartTime()));
        templatePlan.setPlanEndTime(DateUtil.parseDate(templatePlanDto.getPlanEndTime()));
        DateTime firstDateTime = DateUtil.parseDate(templatePlanDto.getFirstTime());
        templatePlan.setFirstTime(firstDateTime);
        templatePlan.setUpdateTime(new Date());
        boolean in = DateUtil.isIn(templatePlan.getFirstTime(), templatePlan.getPlanStartTime(), templatePlan.getPlanEndTime());
        if(!in){
            return DataResult.build9250("首次执行日期必须在计划周期以内！");
        }
        if(firstDateTime.isBefore(DateUtil.date())){
            return DataResult.build9250("首次执行日期必须在当前时间以后！");
        }
        templatePlanMapper.updateByPrimaryKeySelective(templatePlan);
        return DataResult.build9100();
    }

    /*
     * 编辑模版计划任务项
     * */
    @Override
    public DataResult updateTemplateTask(LoginInfo loginInfo, String id, String taskIds) throws Exception {
        TemplatePlanTaskExample templatePlanTaskExample = new TemplatePlanTaskExample();
        templatePlanTaskExample.createCriteria().andTemplateIdEqualTo(Long.parseLong(id));
        templatePlanTaskMapper.deleteByExample(templatePlanTaskExample);
        if(StrUtil.isNotBlank(taskIds)){
            List<Long> taskIdList = new ArrayList<>();
            String[] split = taskIds.split(",");
            for(String splitStr:split){
                taskIdList.add(Long.parseLong(splitStr));
            }
            templatePlanDao.insertPlanTaskList(taskIdList,Long.parseLong(id));
        }
        return DataResult.build9100();
    }

    @Override
    public DataResult updateTemplatePart(LoginInfo loginInfo, String id, String partList) throws Exception {
        TemplatePlanPartExample example = new TemplatePlanPartExample();
        example.createCriteria().andTemplateIdEqualTo(Long.parseLong(id));
        templatePlanPartMapper.deleteByExample(example);
        if(StrUtil.isNotBlank(partList)){
            List<TemplatePlanPart> templatePlanPartList = new ArrayList<>();
            JSONArray jSONArray = JSONUtil.parseArray(partList);
            for(Object obj:jSONArray){
                JSONObject jsonObject = JSONUtil.parseObj(obj);
                Long partId = jsonObject.getLong("partId");
                Integer partNum = jsonObject.getInt("partNum");
                if(partId != null && partNum != null){
                    TemplatePlanPart templatePlanPart = new TemplatePlanPart();
                    templatePlanPart.setTemplateId(Long.parseLong(id));
                    templatePlanPart.setPartId(partId);
                    templatePlanPart.setPartNum(partNum);
                    templatePlanPartList.add(templatePlanPart);
                }

            }
            templatePlanDao.insertPlanPartList(templatePlanPartList);
        }
        return DataResult.build9100();
    }

    @Override
    public DataResult updateTemplateState(LoginInfo loginInfo, String id, String state) {
        long lId = Long.parseLong(id);
        TemplatePlan getTemplatePlan = templatePlanMapper.selectByPrimaryKey(lId);
        int stateInt = Integer.parseInt(state);
        //stateInt = 2 启用 ；3停用 ；4作废
        if(stateInt == 2){
            if (getTemplatePlan.getState() == 3) {
                PlanInfo planInfo = new PlanInfo();
                planInfo.setIsDelete(1);
                PlanInfoExample planInfoExample = new PlanInfoExample();
                PlanInfoExample.Criteria planInfoCriteria = planInfoExample.createCriteria();
                planInfoCriteria.andTemplateIdEqualTo(lId);
                planInfoCriteria.andIsDeleteEqualTo(2);
                planInfoMapper.updateByExampleSelective(planInfo,planInfoExample);
            }
        }else if(stateInt == 3){
            PlanInfo planInfo = new PlanInfo();
            planInfo.setIsDelete(2);
            PlanInfoExample planInfoExample = new PlanInfoExample();
            PlanInfoExample.Criteria planInfoCriteria = planInfoExample.createCriteria();
            planInfoCriteria.andTemplateIdEqualTo(lId);
            planInfoCriteria.andIsGenerateEqualTo(1);
            planInfoMapper.updateByExampleSelective(planInfo,planInfoExample);
        }else if(stateInt == 4){
            if(getTemplatePlan.getState() != 3){
                return DataResult.build9250("停用的模板才能作废！");
            }
            PlanInfoExample planInfoExample = new PlanInfoExample();
            PlanInfoExample.Criteria planInfoCriteria = planInfoExample.createCriteria();
            planInfoCriteria.andTemplateIdEqualTo(lId);
            planInfoCriteria.andIsDeleteEqualTo(2);
            planInfoMapper.deleteByExample(planInfoExample);
        }
        TemplatePlan templatePlan = new TemplatePlan();
        templatePlan.setId(lId);
        templatePlan.setState(stateInt);
        templatePlanMapper.updateByPrimaryKeySelective(templatePlan);
        return DataResult.build9100();
    }

    /*
    * 设备绑定计划
    * */
    @Override
    public DataResult templateBindingEquipment(LoginInfo loginInfo, String emId, String mainTemplateIds, String inspTemplateIds) throws Exception {
        List<EquipmentPlanTemplate> getAllEquipmentTemplate = new ArrayList<>();
        long emIdLong = Long.parseLong(emId);
        Date newDate = new Date();

        if(StrUtil.isNotBlank(mainTemplateIds)){
            String[] split = mainTemplateIds.split(",");
            for(String sp:split){
                EquipmentPlanTemplate equipmentPlanTemplate = new EquipmentPlanTemplate();
                equipmentPlanTemplate.setType(1);
                equipmentPlanTemplate.setEmId(emIdLong);
                equipmentPlanTemplate.setTemplateId(Long.parseLong(sp));
                equipmentPlanTemplate.setCreateTime(newDate);
                getAllEquipmentTemplate.add(equipmentPlanTemplate);
            }
        }

        if(StrUtil.isNotBlank(inspTemplateIds)){
            String[] split = inspTemplateIds.split(",");
            for(String sp:split){
                EquipmentPlanTemplate equipmentPlanTemplate = new EquipmentPlanTemplate();
                equipmentPlanTemplate.setType(2);
                equipmentPlanTemplate.setEmId(emIdLong);
                equipmentPlanTemplate.setTemplateId(Long.parseLong(sp));
                equipmentPlanTemplate.setCreateTime(newDate);
                getAllEquipmentTemplate.add(equipmentPlanTemplate);
            }
        }

        EquipmentPlanTemplateExample emExample = new EquipmentPlanTemplateExample();
        emExample.createCriteria().andEmIdEqualTo(emIdLong);
        List<EquipmentPlanTemplate> selectEquipmentPlanTemplateList = EquipmentPlanTemplateMapper.selectByExample(emExample);
        //绑定全部计划数据,数据库没有数据
        if (CollUtil.isEmpty(selectEquipmentPlanTemplateList)) {
            if (CollUtil.isNotEmpty(getAllEquipmentTemplate)) {
                templatePlanDao.insertEquipmentTemplateList(getAllEquipmentTemplate);
                asyncPlanService.insertPlanInfoByTemplate(getAllEquipmentTemplate);
            }
        } else {
            //数据库有数据
            if(CollUtil.isEmpty(getAllEquipmentTemplate)){
                //删除数据库所有计划数据
                EquipmentPlanTemplateMapper.deleteByExample(emExample);
            } else {
                //获取需要新增的数据
                List<EquipmentPlanTemplate> addCollect = getAllEquipmentTemplate.stream()
                        .filter(a -> selectEquipmentPlanTemplateList.stream().noneMatch(b -> a.getTemplateId().equals(b.getTemplateId())))
                        .collect(Collectors.toList());
                //获取要想删除的数据
                List<EquipmentPlanTemplate> removeCollect = selectEquipmentPlanTemplateList.stream()
                        .filter(a -> getAllEquipmentTemplate.stream().noneMatch(b -> a.getTemplateId().equals(b.getTemplateId())))
                        .collect(Collectors.toList());

                if (CollUtil.isNotEmpty(addCollect)) {
                    templatePlanDao.insertEquipmentTemplateList(addCollect);
                    asyncPlanService.insertPlanInfoByTemplate(addCollect);
                }

                if (CollUtil.isNotEmpty(removeCollect)) {
                    List<Long> ids = removeCollect.stream().map(EquipmentPlanTemplate::getId).collect(Collectors.toList());
                    EquipmentPlanTemplateExample remExample = new EquipmentPlanTemplateExample();
                    remExample.createCriteria().andIdIn(ids);
                    EquipmentPlanTemplateMapper.deleteByExample(remExample);
                }
            }
        }
        return DataResult.build9100();
    }

    /*
     * 绑定计划
     * */
    @Override
    public DataResult templateBindingEquipmentInsp(LoginInfo loginInfo, String emId, String mainTemplateIds, String inspTemplateList) throws Exception {
        List<EquipmentPlanTemplate> getAllEquipmentTemplate = new ArrayList<>();
        long emIdLong = Long.parseLong(emId);
        Date newDate = new Date();

        if(StrUtil.isNotBlank(mainTemplateIds)){
            String[] split = mainTemplateIds.split(",");
            for (String sp : split) {
                EquipmentPlanTemplate equipmentPlanTemplate = new EquipmentPlanTemplate();
                equipmentPlanTemplate.setType(1);
                equipmentPlanTemplate.setEmId(emIdLong);
                equipmentPlanTemplate.setTemplateId(Long.parseLong(sp));
                equipmentPlanTemplate.setCreateTime(newDate);
                getAllEquipmentTemplate.add(equipmentPlanTemplate);
            }
        }

        if(StrUtil.isNotBlank(inspTemplateList)){
            JSONArray jSONArray = JSONUtil.parseArray(inspTemplateList);
            for (Object obj : jSONArray) {
                JSONObject jsonObject = JSONUtil.parseObj(obj);
                Long templateId = jsonObject.getLong("templateId");
                Long employeeId = jsonObject.getLong("employeeId");
                String minuteTime = jsonObject.getStr("minuteTime");
                EquipmentPlanTemplate equipmentPlanTemplate = new EquipmentPlanTemplate();
                equipmentPlanTemplate.setType(2);
                equipmentPlanTemplate.setEmId(emIdLong);
                equipmentPlanTemplate.setTemplateId(templateId);
                equipmentPlanTemplate.setCreateTime(newDate);
                equipmentPlanTemplate.setEmployeeId(employeeId);
                equipmentPlanTemplate.setMinuteTime(minuteTime);
                getAllEquipmentTemplate.add(equipmentPlanTemplate);
            }
        }
        EquipmentPlanTemplateExample emExample = new EquipmentPlanTemplateExample();
        emExample.createCriteria().andEmIdEqualTo(emIdLong);
        List<EquipmentPlanTemplate> selectEquipmentPlanTemplateList = EquipmentPlanTemplateMapper.selectByExample(emExample);
        //绑定全部计划数据,数据库没有数据
        if (CollUtil.isEmpty(selectEquipmentPlanTemplateList)) {
            if (CollUtil.isNotEmpty(getAllEquipmentTemplate)) {
                templatePlanDao.insertEquipmentTemplateList(getAllEquipmentTemplate);
                asyncPlanService.insertPlanInfoByTemplate(getAllEquipmentTemplate);
            }
        } else {
            //数据库有数据
            if(CollUtil.isEmpty(getAllEquipmentTemplate)){
                //删除数据库所有计划数据
                EquipmentPlanTemplateMapper.deleteByExample(emExample);
            } else {
                //获取需要新增的数据
                List<EquipmentPlanTemplate> addCollect = getAllEquipmentTemplate.stream()
                        .filter(a -> selectEquipmentPlanTemplateList.stream().noneMatch(b -> a.getTemplateId().equals(b.getTemplateId())))
                        .collect(Collectors.toList());
                //获取要想删除的数据
                List<EquipmentPlanTemplate> removeCollect = selectEquipmentPlanTemplateList.stream()
                        .filter(a -> getAllEquipmentTemplate.stream().noneMatch(b -> a.getTemplateId().equals(b.getTemplateId())))
                        .collect(Collectors.toList());

                if (CollUtil.isNotEmpty(addCollect)) {
                    templatePlanDao.insertEquipmentTemplateList(addCollect);
                    asyncPlanService.insertPlanInfoByTemplate(addCollect);
                }

                if (CollUtil.isNotEmpty(removeCollect)) {
                    List<Long> ids = removeCollect.stream().map(EquipmentPlanTemplate::getId).collect(Collectors.toList());
                    EquipmentPlanTemplateExample remExample = new EquipmentPlanTemplateExample();
                    remExample.createCriteria().andIdIn(ids);
                    EquipmentPlanTemplateMapper.deleteByExample(remExample);
                }
            }
        }
        return DataResult.build9100();
    }

    /*
    * 查询绑定模版计划
    * */
    @Override
    public DataResult getTemplateBindingEquipment(LoginInfo loginInfo, String emId) throws Exception {
        Map<String, Object> returnMap = new HashMap<>();
        List<Map<String, Object>> mapsOne = templatePlanDao.selectEquipmentTemplateByEmIdOne(Long.parseLong(emId));
        List<Map<String, Object>> mapsTwo = templatePlanDao.selectEquipmentTemplateByEmIdTwo(Long.parseLong(emId));
        returnMap.put("mainTemplate", mapsOne);
        returnMap.put("inspTemplate", mapsTwo);
        return DataResult.build9100(returnMap);
    }

    /*
    * 查询维保计划配置
    * */
    @Override
    public DataResult selectUpkeepTemplateTask(LoginInfo loginInfo, String emId) throws Exception {
        UpkeepTemplateTaskExample example = new UpkeepTemplateTaskExample();
        example.createCriteria().andEmIdEqualTo(Long.parseLong(emId));
        List<UpkeepTemplateTask> upkeepTemplateTasks = upkeepTemplateTaskMapper.selectByExample(example);
        List<Map<String,Object>> list = new ArrayList<>();
        if(CollUtil.isNotEmpty(upkeepTemplateTasks)){
            List<Long> dbTaskIdList = upkeepTemplateTasks.stream().map(UpkeepTemplateTask::getDbTaskId).collect(Collectors.toList());
            UpkeepDbTaskExample dbExample = new UpkeepDbTaskExample();
            dbExample.createCriteria().andIdIn(dbTaskIdList);
            List<UpkeepDbTask> upkeepDbTasks = upkeepDbTaskMapper.selectByExample(dbExample);
            Map<Long, UpkeepDbTask> dbTaskMap = upkeepDbTasks.stream().collect(Collectors.toMap(UpkeepDbTask::getId, t -> t));
            for (UpkeepTemplateTask task : upkeepTemplateTasks) {
                Map<String, Object> map = new HashMap<>();
                UpkeepDbTask upkeepDbTask = dbTaskMap.get(task.getDbTaskId());
                if (upkeepDbTask != null) {
                    map.put("taskName", upkeepDbTask.getTaskName());
                    map.put("taskDesc", upkeepDbTask.getTaskDesc());
                    map.put("remark", upkeepDbTask.getRemark());
                } else {
                    map.put("taskName", "");
                    map.put("taskDesc", "");
                    map.put("remark", "");
                }
                map.put("businessType", task.getBusinessType());
                map.put("modeType", task.getModeType());
                map.put("dateInterval", task.getDateInterval());
                map.put("firstTime", DateUtil.format(task.getFirstTime(), "yyyy-MM-dd"));
                map.put("planStartTime", DateUtil.format(task.getPlanStartTime(), "yyyy-MM-dd"));
                map.put("planEndTime", DateUtil.format(task.getPlanEndTime(), "yyyy-MM-dd"));
                map.put("runningDayTime", task.getRunningDayTime());
                map.put("runningTime", task.getRunningTime());
                map.put("emId", task.getEmId());
                map.put("state", task.getState());
                map.put("id", task.getId());
                map.put("treeId", task.getTreeId());
                map.put("dbTaskId", task.getDbTaskId());
                list.add(map);
            }
        }
        return DataResult.build9100(list);
    }

    /*
     * 保存维保计划配置
     * */
    @Override
    public DataResult insertUpkeepTemplateTask(LoginInfo li, UpkeepTemplateTaskDto upkeepTemplateTaskDto) throws Exception{
        UpkeepTemplateTask templateTask = new UpkeepTemplateTask();
        Integer modeType = Integer.parseInt(upkeepTemplateTaskDto.getModeType());
        templateTask.setModeType(modeType);
        templateTask.setDbTaskId(Long.parseLong(upkeepTemplateTaskDto.getDbTaskId()));
        templateTask.setEmId(Long.parseLong(upkeepTemplateTaskDto.getEmId()));
        templateTask.setTreeId(Long.parseLong(upkeepTemplateTaskDto.getTreeId()));
        templateTask.setState(1);
        templateTask.setFirstTime(DateUtil.parseDate(upkeepTemplateTaskDto.getFirstTime()));
        templateTask.setCreateTime(new Date());
        //执行方式1，定期循环 ；2,运行时长
        if(1 == modeType){
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getBusinessType())){
                return DataResult.build9250("businessType不能为空！");
            }
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getDateInterval())){
                return DataResult.build9250("dateInterval不能为空！");
            }
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getPlanStartTime())){
                return DataResult.build9250("planStartTime不能为空！");
            }
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getPlanEndTime())){
                return DataResult.build9250("planEndTime不能为空！");
            }
            templateTask.setBusinessType(Integer.parseInt(upkeepTemplateTaskDto.getBusinessType()));
            templateTask.setDateInterval(Integer.parseInt(upkeepTemplateTaskDto.getDateInterval()));
            templateTask.setPlanStartTime(DateUtil.parseDate(upkeepTemplateTaskDto.getPlanStartTime()));
            templateTask.setPlanEndTime(DateUtil.parseDate(upkeepTemplateTaskDto.getPlanEndTime()));
        }else if(2 == modeType){
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getRunningTime())){
                return DataResult.build9250("runningTime不能为空！");
            }
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getRunningDayTime())){
                return DataResult.build9250("runningDayTime不能为空！");
            }
            templateTask.setRunningTime(Integer.parseInt(upkeepTemplateTaskDto.getRunningTime()));
            templateTask.setRunningDayTime(Integer.parseInt(upkeepTemplateTaskDto.getRunningDayTime()));
        }else {
            return DataResult.build9250("执行方式未知。保存失败！");
        }
        upkeepTemplateTaskMapper.insert(templateTask);

        //保存零件
        if (StrUtil.isNotBlank(upkeepTemplateTaskDto.getPartList())) {
            JSONArray jSONArray = JSONUtil.parseArray(upkeepTemplateTaskDto.getPartList());
            for (Object obj : jSONArray) {
                JSONObject jsonObject = JSONUtil.parseObj(obj);
                Long partId = jsonObject.getLong("partId");
                Integer partNum = jsonObject.getInt("partNum");
                if (partId != null && partNum != null) {
                    UpkeepTemplateTaskPart upkeepPart = new UpkeepTemplateTaskPart();
                    upkeepPart.setTemplateTaskId(templateTask.getId());
                    upkeepPart.setPartId(partId);
                    upkeepPart.setPartNum(partNum);
                    upkeepPart.setCreateTime(new Date());
                    upkeepTemplateTaskPartMapper.insert(upkeepPart);
                }
            }
        }
        return DataResult.build9100();
    }

    /*
    * 根据ID查询维保配置详情
    * */
    @Override
    public DataResult getUpkeepTemplateTaskById(LoginInfo li, long id) throws Exception {
        Map<String, Object> map = new HashMap<>();
        UpkeepTemplateTask task = upkeepTemplateTaskMapper.selectByPrimaryKey(id);
        if(task != null){
            UpkeepTemplateTaskPartExample example = new UpkeepTemplateTaskPartExample();
            example.createCriteria().andTemplateTaskIdEqualTo(task.getId());
            List<UpkeepTemplateTaskPart> upkeepTemplateTaskParts = upkeepTemplateTaskPartMapper.selectByExample(example);
            UpkeepDbTask upkeepDbTask = upkeepDbTaskMapper.selectByPrimaryKey(task.getDbTaskId());
            map.put("businessType", task.getBusinessType());
            map.put("modeType", task.getModeType());
            map.put("dateInterval", task.getDateInterval());
            map.put("firstTime", DateUtil.format(task.getFirstTime(), "yyyy-MM-dd"));
            map.put("planStartTime", DateUtil.format(task.getPlanStartTime(), "yyyy-MM-dd"));
            map.put("planEndTime", DateUtil.format(task.getPlanEndTime(), "yyyy-MM-dd"));
            map.put("runningDayTime", task.getRunningDayTime());
            map.put("runningTime", task.getRunningTime());
            map.put("emId", task.getEmId());
            map.put("state", task.getState());
            map.put("id", task.getId());
            map.put("treeId", task.getTreeId());
            map.put("dbTaskId", task.getDbTaskId());
            if (upkeepDbTask != null) {
                map.put("taskName", upkeepDbTask.getTaskName());
                map.put("taskDesc", upkeepDbTask.getTaskDesc());
                map.put("remark", upkeepDbTask.getRemark());
            } else {
                map.put("taskName", "");
                map.put("taskDesc", "");
                map.put("remark", "");
            }
            List<Map<String, Object>> list = new ArrayList<>();
            for (UpkeepTemplateTaskPart part : upkeepTemplateTaskParts) {
                PartInfo pi = partInfoMapper.selectByPrimaryKey(part.getPartId());
                Map<String, Object> forMap = new HashMap<>();
                forMap.put("partId",part.getPartId());
                forMap.put("partNum",part.getPartNum());
                forMap.put("code", pi.getCode());
                forMap.put("name", pi.getName());
                forMap.put("specs", pi.getSpecs());
                forMap.put("brand", pi.getBrand());
                forMap.put("unit", pi.getUnit());
                forMap.put("price", pi.getPrice().toPlainString());
                forMap.put("stock", pi.getStock());
                forMap.put("warnStock", pi.getWarnStock());
                forMap.put("maxStock", pi.getMaxStock());
                forMap.put("nature", pi.getNature());
                forMap.put("tech", pi.getTech());
                list.add(forMap);
            }
            map.put("partList",list);
        }
        return DataResult.build9100(map);
    }

    @Override
    public DataResult updateUpkeepTemplateTask(LoginInfo li, UpkeepTemplateTaskDto upkeepTemplateTaskDto) throws Exception{
        if(StrUtil.isBlank(upkeepTemplateTaskDto.getId())){
            return DataResult.build9250("id不能为空！");
        }
        Long id = Long.parseLong(upkeepTemplateTaskDto.getId());
        UpkeepTemplateTask upkeepTemplateTask = upkeepTemplateTaskMapper.selectByPrimaryKey(id);
        if(upkeepTemplateTask.getState() != 1){
            return DataResult.build9250("草稿状态才能编辑！");
        }

        UpkeepTemplateTask templateTask = new UpkeepTemplateTask();
        templateTask.setId(id);
        Integer modeType = Integer.parseInt(upkeepTemplateTaskDto.getModeType());
        templateTask.setModeType(modeType);
        templateTask.setDbTaskId(Long.parseLong(upkeepTemplateTaskDto.getDbTaskId()));
        templateTask.setEmId(Long.parseLong(upkeepTemplateTaskDto.getEmId()));
        templateTask.setTreeId(Long.parseLong(upkeepTemplateTaskDto.getTreeId()));
        templateTask.setState(upkeepTemplateTask.getState());
        templateTask.setFirstTime(DateUtil.parseDate(upkeepTemplateTaskDto.getFirstTime()));
        templateTask.setCreateTime(upkeepTemplateTask.getCreateTime());
        //执行方式1，定期循环 ；2,运行时长
        if(1 == modeType){
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getBusinessType())){
                return DataResult.build9250("businessType不能为空！");
            }
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getDateInterval())){
                return DataResult.build9250("dateInterval不能为空！");
            }
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getPlanStartTime())){
                return DataResult.build9250("planStartTime不能为空！");
            }
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getPlanEndTime())){
                return DataResult.build9250("planEndTime不能为空！");
            }
            templateTask.setBusinessType(Integer.parseInt(upkeepTemplateTaskDto.getBusinessType()));
            templateTask.setDateInterval(Integer.parseInt(upkeepTemplateTaskDto.getDateInterval()));
            templateTask.setPlanStartTime(DateUtil.parseDate(upkeepTemplateTaskDto.getPlanStartTime()));
            templateTask.setPlanEndTime(DateUtil.parseDate(upkeepTemplateTaskDto.getPlanEndTime()));
        }else if(2 == modeType){
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getRunningTime())){
                return DataResult.build9250("runningTime不能为空！");
            }
            if(StrUtil.isBlank(upkeepTemplateTaskDto.getRunningDayTime())){
                return DataResult.build9250("runningDayTime不能为空！");
            }
            templateTask.setRunningTime(Integer.parseInt(upkeepTemplateTaskDto.getRunningTime()));
            templateTask.setRunningDayTime(Integer.parseInt(upkeepTemplateTaskDto.getRunningDayTime()));
        }else {
            return DataResult.build9250("执行方式未知。保存失败！");
        }
        upkeepTemplateTaskMapper.updateByPrimaryKey(templateTask);

        //保存零件
        UpkeepTemplateTaskPartExample partExample = new UpkeepTemplateTaskPartExample();
        partExample.createCriteria().andTemplateTaskIdEqualTo(templateTask.getId());
        upkeepTemplateTaskPartMapper.deleteByExample(partExample);
        if (StrUtil.isNotBlank(upkeepTemplateTaskDto.getPartList())) {
            JSONArray jSONArray = JSONUtil.parseArray(upkeepTemplateTaskDto.getPartList());
            for (Object obj : jSONArray) {
                JSONObject jsonObject = JSONUtil.parseObj(obj);
                Long partId = jsonObject.getLong("partId");
                Integer partNum = jsonObject.getInt("partNum");
                if (partId != null && partNum != null) {
                    UpkeepTemplateTaskPart upkeepPart = new UpkeepTemplateTaskPart();
                    upkeepPart.setTemplateTaskId(templateTask.getId());
                    upkeepPart.setPartId(partId);
                    upkeepPart.setPartNum(partNum);
                    upkeepPart.setCreateTime(new Date());
                    upkeepTemplateTaskPartMapper.insert(upkeepPart);
                }
            }
        }

        return DataResult.build9100();
    }

    /*
    * 根据ID删除维保计划配置
    * */
    @Override
    public DataResult deleteUpkeepTemplateTask(LoginInfo li, Long id) throws Exception {
        UpkeepTemplateTask upkeepTemplateTask = upkeepTemplateTaskMapper.selectByPrimaryKey(id);
//        if(upkeepTemplateTask.getState() != 1){
//            return DataResult.build9250("草稿状态才能删除！");
//        }
        upkeepTemplateTaskMapper.deleteByPrimaryKey(id);
        return DataResult.build9100();
    }

    /*
     * 修改维保计划配置状态
     * state = 1,草稿 2，启用；3，停用；4，作废
     * */
    @Override
    public DataResult updateUpkeepTemplateTaskState(LoginInfo li, long id, int state) throws Exception {
        UpkeepTemplateTask getUpkeepTemplateTask = upkeepTemplateTaskMapper.selectByPrimaryKey(id);
//        if(state == 2){
//            if(getUpkeepTemplateTask.getState() != 1 && getUpkeepTemplateTask.getState() != 4){
//                return DataResult.build9250("草稿状态才能启用！");
//            }
//        }
        if(state == 3){
            if(getUpkeepTemplateTask.getState() != 2){
                return DataResult.build9250("启用状态才能停用！");
            }
        }else if(state == 4){
            if(getUpkeepTemplateTask.getState() != 3){
                return DataResult.build9250("停用状态才能作废！");
            }
        }
        UpkeepTemplateTask upkeepTemplateTask = new UpkeepTemplateTask();
        upkeepTemplateTask.setState(state);
        upkeepTemplateTask.setId(id);
        upkeepTemplateTaskMapper.updateByPrimaryKeySelective(upkeepTemplateTask);
        //执行方式1，定期循环 ；2,运行时长
        getUpkeepTemplateTask.setState(state);
        if (getUpkeepTemplateTask.getModeType() == 1) {
            insertPlanInfoByUpkeepMode(getUpkeepTemplateTask);
        } else if (getUpkeepTemplateTask.getModeType() == 2) {
            insertPlanInfoByUpkeep(getUpkeepTemplateTask);
        }
        return DataResult.build9100();
    }


    private void insertPlanInfoByUpkeepMode(UpkeepTemplateTask upkeepTemplateTask) {
        //2，启用；4，作废
        if(upkeepTemplateTask.getState() == 2){
            insertPlanInfoByUpkeepState(upkeepTemplateTask);
        }else if(upkeepTemplateTask.getState() == 4){
            deletePlanInfoByUpkeepState(upkeepTemplateTask);
        }
    }

    private void insertPlanInfoByUpkeep(UpkeepTemplateTask upkeepTemplateTask) {
        //2，启用；4，作废
        if(upkeepTemplateTask.getState() == 2){
            EquipmentInfo equipmentInfo = equipmentInfoMapper.selectByPrimaryKey(upkeepTemplateTask.getEmId());
            UpkeepDbTask upkeepDbTask = upkeepDbTaskMapper.selectByPrimaryKey(upkeepTemplateTask.getDbTaskId());
            PlanInfo planInfo = new PlanInfo();
            planInfo.setEmId(upkeepTemplateTask.getEmId());
            planInfo.setTreeId(upkeepTemplateTask.getTreeId());
            planInfo.setPlanType(1);
            planInfo.setTemplateId(upkeepTemplateTask.getId());
            planInfo.setTemplateName(equipmentInfo.getEmName() + "-" + upkeepDbTask.getTaskName());
            planInfo.setIsGenerate(1);
            planInfo.setIsDelete(1);
            planInfo.setChangeTime(upkeepTemplateTask.getFirstTime());
            planInfo.setYear(DateUtil.year(upkeepTemplateTask.getFirstTime()));
            planInfo.setMonth(DateUtil.month(upkeepTemplateTask.getFirstTime())+1);
            planInfo.setDay(DateUtil.dayOfMonth(upkeepTemplateTask.getFirstTime()));
            planInfo.setCreateTime(new Date());
            planInfoMapper.insertSelective(planInfo);
        }else if(upkeepTemplateTask.getState() == 4){
            deletePlanInfoByUpkeepState(upkeepTemplateTask);
        }
    }

    /*
     * 生成维保
     * */
    private void insertPlanInfoByUpkeepState(UpkeepTemplateTask upkeepTemplateTask){
        Date firstTime = upkeepTemplateTask.getFirstTime();
        Date planEndTime = DateUtil.endOfDay(upkeepTemplateTask.getPlanEndTime());
        int businessType = upkeepTemplateTask.getBusinessType();
        int dateInterval = upkeepTemplateTask.getDateInterval();
        EquipmentInfo equipmentInfo = equipmentInfoMapper.selectByPrimaryKey(upkeepTemplateTask.getEmId());
        UpkeepDbTask upkeepDbTask = upkeepDbTaskMapper.selectByPrimaryKey(upkeepTemplateTask.getDbTaskId());
        List<PlanInfo> planInfoList = new ArrayList<>();
        while ((firstTime.before(planEndTime) || firstTime.equals(planEndTime))){
            PlanInfo planInfo = new PlanInfo();
            planInfo.setEmId(upkeepTemplateTask.getEmId());
            planInfo.setTreeId(upkeepTemplateTask.getTreeId());
            planInfo.setPlanType(1);
            planInfo.setTemplateId(upkeepTemplateTask.getId());
            planInfo.setTemplateName(equipmentInfo.getEmName() + "-" + Optional.ofNullable(upkeepDbTask).map(UpkeepDbTask::getTaskName).orElse(""));
            planInfo.setIsGenerate(1);
            planInfo.setIsDelete(1);
            planInfo.setChangeTime(firstTime);
            planInfo.setYear(DateUtil.year(firstTime));
            planInfo.setMonth(DateUtil.month(firstTime)+1);
            planInfo.setDay(DateUtil.dayOfMonth(firstTime));
            planInfoList.add(planInfo);
            //1日保养，2周保养，3月保养
            if(1==businessType){
                firstTime = DateUtil.offsetDay(firstTime,dateInterval);
            }else if(2==businessType){
                firstTime = DateUtil.offsetWeek(firstTime,dateInterval);
            }else if(3==businessType){
                firstTime = DateUtil.offsetMonth(firstTime,dateInterval);
            }
        }
        templatePlanDao.insertPlanInfoList(planInfoList);
    }

    /*
     * 删除巡检计划
     * */
    private void deletePlanInfoByUpkeepState(UpkeepTemplateTask upkeepTemplateTask){
        PlanInfoExample example = new PlanInfoExample();
        PlanInfoExample.Criteria criteria = example.createCriteria();
        criteria.andPlanTypeEqualTo(1);
        criteria.andTemplateIdEqualTo(upkeepTemplateTask.getId());
        criteria.andIsGenerateEqualTo(1);
        planInfoMapper.deleteByExample(example);
    }


}
